import React, { useState, useEffect } from "react";
import { createRoot } from "react-dom/client";
import { message } from "antd";
import { ConfigLayout, TabContentRenderer, FontStyleProvider } from '../components';
import { ServiceManager } from '../services/ServiceManager';
import { ValidationResult, LLMProvider, ImportResult } from '../types';
import { ConfigState } from '../components/TabContentRenderer';

const OptionsPage = () => {
  const [serviceManager] = useState(() => ServiceManager.getInstance());
  const [activeTab, setActiveTab] = useState<string>('llm-config');
  
  // 统一的配置状态
  const [config, setConfig] = useState<ConfigState>({
    llm: {
      provider: "anthropic" as LLMProvider,
      apiKey: "",
      modelName: "claude-sonnet-4-20250514",
      options: {
        baseURL: "https://api.anthropic.com/v1",
      },
    },
    mcp: {
      configs: [],
    },
    advanced: {
      theme: 'light',
      language: 'zh',
      autoSave: true,
    },
    ui: {
      activeTab: 'llm-config',
      isLoading: false,
      validationResults: {},
    },
  });

  useEffect(() => {
    // 初始化服务管理器
    serviceManager.initialize();
    
    // 加载保存的配置
    loadConfigurations();
    
    // 加载上次选中的标签页
    chrome.storage.local.get(['activeConfigTab'], (result) => {
      if (result.activeConfigTab) {
        setActiveTab(result.activeConfigTab);
      }
    });
  }, [serviceManager]);

  const loadConfigurations = async () => {
    try {
      // 加载 LLM 配置
      chrome.storage.sync.get(['llmConfig'], (result) => {
        if (result.llmConfig) {
          if (result.llmConfig.llm === "") {
            result.llmConfig.llm = "anthropic";
          }
          setConfig(prev => ({
            ...prev,
            llm: result.llmConfig
          }));
        }
      });
      
      // 加载 MCP 配置
      chrome.storage.sync.get(['mcpConfig'], (result) => {
        if (result.mcpConfig) {
          setConfig(prev => ({
            ...prev,
            mcp: { configs: result.mcpConfig }
          }));
        }
      });
      
      // 加载高级配置
      chrome.storage.sync.get(['advancedConfig'], (result) => {
        if (result.advancedConfig) {
          setConfig(prev => ({
            ...prev,
            advanced: result.advancedConfig
          }));
        }
      });
    } catch (error) {
      console.error('加载配置失败:', error);
      message.error('加载配置失败');
    }
  };

  const handleTabChange = (tab: string) => {
    setActiveTab(tab);
    setConfig(prev => ({
      ...prev,
      ui: { ...prev.ui, activeTab: tab }
    }));
  };

  const handleConfigChange = (newConfig: Partial<ConfigState>) => {
    setConfig(prev => ({
      ...prev,
      ...newConfig
    }));
  };
  
  // 处理配置导入
  const handleConfigImported = (result: ImportResult) => {
    // 重新加载配置
    loadConfigurations();
    message.success('配置已更新，请重新验证 API Key');
  };

  return (
    <ConfigLayout
      activeTab={activeTab}
      onTabChange={handleTabChange}
    >
      <TabContentRenderer
        activeTab={activeTab}
        config={config}
        onConfigChange={handleConfigChange}
        onConfigImported={handleConfigImported}
      />
    </ConfigLayout>
  );
};

// 确保 DOM 元素存在
const rootElement = document.getElementById("root");
if (!rootElement) {
  throw new Error('Root element not found');
}

const root = createRoot(rootElement);

root.render(
  <React.StrictMode>
    <FontStyleProvider>
      <OptionsPage />
    </FontStyleProvider>
  </React.StrictMode>
);
